import { useEffect, useMemo, useState } from 'react'
import { useMemoizedFn } from 'ahooks'
import _ from 'lodash'
import { Badge, Button, Input, message, Modal, Popover, Select } from 'antd'
import { RowSelectionOptions, SelectionChangedEvent } from '@ag-grid-community/core'

import { CusAgGrid, ICusAgGridProps } from '@/components/CusAgGrid'
import { UnifiedPagination } from '@/components/UnifiedPagination'
import { RouteTplShow } from '@oBiz/components/FieldShowComponents'
import { globalPopupSlot } from '../../globalPopupSlot'
import { addAGCellTexty } from '../addTexty'
import { ITplRouteListItem, TCellParams, TCol } from './interface'
import { defaultParams, useBoundStore } from './store'
import { useTplRouteList } from './useTplRouteList'
import { getBooleanName, getLogisticsStatusName, getRouteNodeName, getRouteTypeName, popupSlot } from './utils'
import styles from './styles.module.less'

const updatePopup = globalPopupSlot.insert(null)

interface IRouteTemplateListModalProps {
  /** title标题 */
  title?: string
  /** 成功时的回调 */
  onSuccess?: (list: ITplRouteListItem[]) => void
}
/** 路由模板item类型 */
export type { ITplRouteListItem }

const Cell = (p: TCellParams) => {
  const { field } = p.colDef || {}
  switch (field) {
    case 'templateCn':
    case 'templateEn': {
      const { value } = p as TCellParams<'templateCn' | 'templateEn'>
      return <RouteTplShow value={value} />
    }
    case 'dynamicField': {
      const { data: { dynamicFieldList } = {} } = p as TCellParams<'dynamicField'>
      if (!dynamicFieldList?.length) return
      return (
        <Popover
          content={
            dynamicFieldList.length > 1 && (
              <div style={{ maxHeight: 200, minWidth: 130, overflow: 'auto' }}>
                {dynamicFieldList.map(d => (
                  <div key={d}>{d}</div>
                ))}
              </div>
            )
          }
        >
          <a>
            {dynamicFieldList[0].replace(/^\s*{{(.+)}}\s*$/, '$1')}
            {dynamicFieldList.length > 1 && `(${dynamicFieldList.length})`}
          </a>
        </Popover>
      )
    }
    case 'routeType': {
      const { value, valueFormatted } = p as TCellParams<'routeType'>
      if (value == null) return
      return <Badge color={value === 1 ? 'green' : 'red'} text={valueFormatted || value} />
    }
    default: {
      return addAGCellTexty(p)
    }
  }
}

export const RouteTemplateListModal = Object.assign(
  ({ onSuccess, title, destroy }: IRouteTemplateListModalProps & { destroy: () => void }) => {
    useTplRouteList() // 放最顶部
    const { open, onHide, afterOpenChange } = popupSlot.useAntdPopupAnimation(destroy)
    const [activeTemplate, setActiveTemplate] = useState<ITplRouteListItem[]>([])
    const gridRef = useBoundStore(v => v.gridRef)
    const loading = useBoundStore(v => v.request?.loading)
    const data = useBoundStore(v => v.request?.data)
    const page = useBoundStore(v => v.reqData.page)
    const size = useBoundStore(v => v.reqData.size)
    const reqData = useBoundStore(v => v.reqData)
    const setReqData = useBoundStore(v => v.setReqData)
    const getData = useBoundStore(v => v.getData)

    // 列配置
    const defaultColDef = useMemo<Partial<TCol>>(
      () => ({
        flex: 1,
        minWidth: 121,
        sortable: false,
        cellRenderer: Cell,
      }),
      [],
    )
    const columnDefs = useMemo(
      () => [
        {
          field: 'routeNo',
          headerName: '路由编号',
          flex: 0.01,
        } satisfies TCol<'routeNo'>,
        {
          field: 'templateCn',
          headerName: '中文模板',
          flex: 2,
          minWidth: 121 * 2,
          autoHeight: true,
          wrapText: true,
        } satisfies TCol<'templateCn'>,
        {
          field: 'templateEn',
          headerName: '英文模板',
          flex: 2,
          minWidth: 121 * 2,
          autoHeight: true,
          wrapText: true,
        } satisfies TCol<'templateEn'>,
        // {
        //   field: 'dynamicField',
        //   headerName: '动态字段',
        //   minWidth: 160,
        // } satisfies TCol<'dynamicField'>,
        {
          field: 'routeNode',
          headerName: '路由节点',
          valueFormatter: ({ value }) => getRouteNodeName(value) || '',
        } satisfies TCol<'routeNode'>,
        {
          field: 'logisticsStatus',
          headerName: '物流状态',
          flex: 0.01,
          minWidth: 114,
          valueFormatter: ({ value }) => getLogisticsStatusName(value) || '',
        } satisfies TCol<'logisticsStatus'>,
        {
          field: 'routeType',
          headerName: '路由类型',
          flex: 0.01,
          minWidth: 114,
          valueFormatter: ({ value }) => getRouteTypeName(value) || '',
        } satisfies TCol<'routeType'>,
        {
          field: 'actionFlag',
          headerName: '需跟进',
          flex: 0.01,
          minWidth: 100,
          valueFormatter: ({ value }) => getBooleanName(value) || '',
        } satisfies TCol<'actionFlag'>,
        {
          field: 'visibleFlag',
          headerName: '客户可见',
          flex: 0.01,
          minWidth: 114,
          valueFormatter: ({ value }) => getBooleanName(value) || '',
        } satisfies TCol<'visibleFlag'>,
      ],
      [],
    )

    // 分页器
    const statusBar = useMemo<ICusAgGridProps['statusBar']>(() => {
      return {
        statusPanels: [
          {
            statusPanel: UnifiedPagination,
            statusPanelParams: UnifiedPagination.defineProps({
              current: page,
              pageSize: size,
              total: data?.total,
              onChange: (page, size) => {
                setReqData({ page, size })
                getData(true)
              },
            }),
          },
        ],
      }
    }, [data?.total, getData, page, setReqData, size])

    const rowSelection = useMemo<RowSelectionOptions | 'single' | 'multiple'>(() => {
      return { mode: 'multiRow', headerCheckbox: false }
    }, [])

    // 查询
    const handleQuery = () => {
      const req = { page: 1 }
      setReqData(req)
      getData(true)
    }

    // 列表勾选
    const onSelectionChanged = (event: SelectionChangedEvent<ITplRouteListItem>) => {
      const selectRows = event.api.getSelectedRows()
      setActiveTemplate(selectRows)
    }

    // 提交
    const submitHandler = useMemoizedFn(() => {
      if (activeTemplate.length <= 0) {
        return message.warning('请选择一个路由模板!')
      }
      onSuccess?.(activeTemplate)
      onHide()
    })

    // 清理
    useEffect(() => () => useBoundStore.setState(useBoundStore.getInitialState(), true), [])

    return (
      <Modal
        title={title || '添加路由'}
        width={1500}
        onCancel={onHide}
        open={open}
        afterOpenChange={afterOpenChange}
        onOk={submitHandler}
      >
        <div className={styles.box}>
          <div className={styles.header}>
            <div className={styles.header_filter}>
              <span className={styles.header_filter_span}>物流状态</span>
              <Select
                style={{ width: '150px' }}
                placeholder="请选择物流状态"
                options={getLogisticsStatusName.valueList2.map(v => ({
                  label: getLogisticsStatusName(v),
                  value: v,
                }))}
                value={reqData.logisticsStatus}
                onChange={v => setReqData({ logisticsStatus: v ?? undefined })}
              />
              <span className={styles.header_filter_span}>节点</span>
              <Select
                style={{ width: '150px' }}
                placeholder="请选择路由节点"
                options={getRouteNodeName.valueList.map(d => ({ label: getRouteNodeName(d), value: d }))}
                value={reqData.routeNode}
                allowClear
                onChange={v => setReqData({ routeNode: v ?? undefined })}
              />
              <span className={styles.header_filter_span}>中文模板</span>
              <Input
                style={{ width: '250px' }}
                placeholder="请输入中文模板"
                value={reqData.templateCn}
                onChange={e => setReqData({ templateCn: e.target.value || undefined })}
              />
              <Button type="primary" style={{ margin: '0 10px' }} onClick={handleQuery}>
                查询
              </Button>
              <Button
                onClick={() => {
                  setReqData({ ..._.omit(defaultParams, ['size']), page: 1 })
                  getData(true)
                }}
              >
                重置
              </Button>
            </div>
          </div>
          <div className={styles.main}>
            <CusAgGrid<ITplRouteListItem>
              ref={gridRef}
              loading={loading}
              rowData={data?.records}
              defaultColDef={defaultColDef}
              columnDefs={columnDefs}
              statusBar={statusBar}
              rowSelection={rowSelection}
              onSelectionChanged={onSelectionChanged}
            />
          </div>
        </div>
      </Modal>
    )
  },
  {
    open: (props: IRouteTemplateListModalProps) => {
      updatePopup(<RouteTemplateListModal {...props} destroy={() => updatePopup(null)} />)
    },
  },
)
